#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

ENB = 18  #使能信号
INC = 23  #信号输入1
IND = 24  #信号输入2

GPIO.setwarnings(False)  #关闭警告信息

def setup(enable_pin,in1_pin,in2_pin):
    '''初始化引脚'''
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(enable_pin, GPIO.OUT)
    GPIO.setup(in1_pin, GPIO.OUT)
    GPIO.setup(in2_pin, GPIO.OUT)
    
def pwm(enable_pin): 
    '''初始化PWM（脉宽调制）'''   
    pwm = GPIO.PWM(enable_pin, 500)
    pwm.start(0)
    return pwm

def changespeed(pwm,speed):
    '''通过改变占空比改变马达转速'''
    pwm.ChangeDutyCycle(speed)
    
def clockwise(in1_pin,in2_pin):
    '''马达顺时针转的信号'''
    GPIO.output(in1_pin, 1)    
    GPIO.output(in2_pin, 0)
 
def counter_clockwise(in1_pin,in2_pin):
    '''马达逆时针转的信号'''
    GPIO.output(in1_pin, 0)
    GPIO.output(in2_pin, 1)
    
def brake(pwm,in1_pin,in2_pin):
    '''马达制动的信号'''
    GPIO.output(in1_pin, 0)
    GPIO.output(in2_pin, 0)
    changespeed(pwm,100) 
    #使能信号为高电平，IN1和IN2都为0或1时马达制动

def loop():
    while True:
        '''通过输入的命令改变马达转动'''
        cmd = input("Command, f/r/b 0..9, E.g. f5 :")
        direction = cmd[0]
        if direction == "f":
            clockwise(INC,IND)
        if direction == "r":
            counter_clockwise(INC,IND)
        if direction == "b": #刹车制动，
            brake(ENB_pwm,INC,IND)
            continue
            
        speed = int(cmd[1]) * 10 #通过输入0~9的数字更改占空比0~90%
        changespeed(ENB_pwm,speed)

def destroy():
    ENB_pwm.stop()
    GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
    
    try:
        setup(ENB,INC,IND) #初始化引脚
        ENB_pwm=pwm(ENB)   #初始化PWM
        loop()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed
        destroy()
    finally:
        destroy()
